package com.hzeport.bgs22emduty.inbound.api;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.Appendix;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/file")
@Api(value = "file", tags = "文件上传和下载")
@Slf4j
public class FileController {

    private final SystemConfig systemConfig;

    private final AppendixRepository appendixRepository;

    private final LoginCompoentService loginCompoentService;


    @ApiOperation(value = "上传", notes = "上传")
    @PostMapping("/upload")
    public BaseResult<FileVO> upload(@RequestPart List<MultipartFile> multipartFile) throws IOException {
        UserInfoDetailVO userInfoDetailVO=loginCompoentService.getUserInfo();
        String originalFilename = multipartFile.get(0).getOriginalFilename();
        assert originalFilename != null;
        String[]temp= originalFilename.split("\\.");
        String split = temp[temp.length-1];
        FileVO fileVO = new FileVO();
        fileVO.setSourceFileName(multipartFile.get(0).getOriginalFilename());
        String fileName = UuidUtils.generateUuid()+"."+split;
        fileVO.setCurrentFileName(fileName);
        Appendix appendix = new Appendix();
        appendix.setSourceFileName(fileVO.getSourceFileName());
        appendix.setCurrentFileName(fileVO.getCurrentFileName());
        appendix.setFileUrl(systemConfig.getFileUrl());
        appendix.setCreateBy(userInfoDetailVO.getUserId());
        appendix.setCreateTime(LocalDateTime.now());
        appendix.setUpdateBy(userInfoDetailVO.getUserId());
        appendix.setUpdateTime(LocalDateTime.now());
        appendix.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
        appendixRepository.save(appendix);
        fileVO.setId(appendix.getId());
//        multipartFile.transferTo(new File(systemConfig.getFileUrl() + fileName));
        multipartFile.get(0).transferTo(FileUtil.newFile(systemConfig.getFileUrl() + fileName));
        return BaseResult.ok(fileVO);
    }

    @ApiOperation(value = "下载", notes = "下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String fileName) throws IOException {
        String finalFileName=systemConfig.getFileUrl() + File.separator + fileName;
        File file = FileUtil.newFile(finalFileName);
        log.info("获取文件"+finalFileName);
        if(!file.exists()){
            log.info("找不到文件"+finalFileName);
            return;
        }
        log.info("获取文件成功"+finalFileName);
//        FileInputStream fileInputStream = new FileInputStream(file);
        //通用文件contentType
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//        ServletOutputStream outputStream = response.getOutputStream();
//        byte[] bytes = new byte[1024];
//        int len;
//        while ((len = fileInputStream.read(bytes)) != -1){
//            outputStream.write(bytes,0,len);
//        }
//        outputStream.flush();
//        outputStream.close();

        try (FileInputStream inputStream = new FileInputStream(file)){
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        }catch (IOException e){
            log.error("记录到异常", e);
        }
    }

}
